<template>
    <!-- 类目组件 -->
    <div class="category" v-if="isShow">
        <div class="reserve_seat"></div>
        <van-nav-bar :title="title" left-arrow @click-left="navLeftClick" />
        <div class="category_box">
            <div class="category_box_left">
                <div v-for="item in treeData" :key="item.categoryId"
                    :class="{ category_box_left_item: true, category_box_left_item_active: item.categoryId == oneData?.categoryId }"
                    @click="oneClick(item)">
                    {{ item.categoryName }}
                </div>
            </div>
            <div class="category_box_right">
                <div class="category_box_right_top" @click="twoClick(1, oneData)">
                    <div class="category_box_right_top_img" v-if="oneData">
                        {{ oneData.categoryName }}
                        <img v-if="isActive(oneData?.categoryId)" class="category_box_right_top_is true"
                            src="@/assets/commodity/icon_daxuanzhong.png" alt="">
                        <div v-else class="category_box_right_top_is false"></div>
                    </div>
                </div>
                <div class="category_box_right_slide">
                    <div class="category_box_right_div" v-for="(item) in itemChildrenData" :key="item.categoryId">
                        <div :class="{ right_div_title: true, right_div_title_active: isActive(item.categoryId) }"
                            @click="twoClick(2, oneData, item)">
                            <span>{{ item.categoryName }}</span>
                            <img v-if="isActive(item.categoryId)" class="right_div_title_is"
                                src="@/assets/commodity/icon_xuanzhong.png" alt="">
                            <div v-else class="right_div_title_is false"></div>
                        </div>
                        <div class=" right_div_title_flex">
                            <div v-if="item.children && item.children.length != 0" class="right_div_title_flex_item"
                                v-for="(ite) in item.children" :key="ite.categoryId"
                                @click="twoClick(3, oneData, item, ite)">
                                <div
                                    :class="{ right_div_title_flex_item_div: true, right_div_title_flex_item_active: isActive(ite.categoryId) }">
                                    {{ ite.categoryName }}</div>
                            </div>
                            <div v-else class="right_div_title_flex_item_false">暂无类目</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="category_footer">
            <div class="category_footer_button">
                <div class="category_footer_reset" @click="reset">重置</div>
                <div class="category_footer_submit" @click="submit">完成</div>
            </div>
        </div>
    </div>
</template>
<script setup lang="ts">
import { ref, defineProps, defineEmits } from 'vue'
import { categoryList } from '@/api/productList/index'
// isShow：组件开关，title：顶部标题名称，value：双向数据绑定值，multiple：是否开启多选模式
const props = defineProps({ isShow: { default: () => false }, title: { default: '分类' }, value: { type: [String, Array], default: () => '' }, multiple: { default: false } })
const emit = defineEmits(['leftClick', 'onSubmit', 'update:value'])
// 左侧菜单选择
const oneData = ref<any>({})
// 二级三级类目选择
const itemChildrenData = ref<Array<any>>([])
// 类目数据
const treeData = ref<Array<any>>([])
// 保存选中的id，高亮选项
const radioId = ref('')
const radioValue = ref<any>([])
// 保存选中的多选id数组
const multiplevValue = ref<any>([])

// 获取类目数据
const getList = async () => {
    const { data = [] } = await categoryList({})
    // treeData.value = removeInvalidNodes(data || [], 'categoryStatus')
    treeData.value = data
    // 将第一条数据跟子数据展示出来
    if (data && data.length) {
        oneData.value = data[0]
        if (data[0].children && data[0].children.length) {
            itemChildrenData.value = data[0].children
        }
    }
}
getList()

// 头部导航点击事件
const navLeftClick = () => {
    emit('leftClick')
}
// 左侧目录点击事件
const oneClick = (row: any) => {
    oneData.value = row
    itemChildrenData.value = row.children
}
// 右侧目录点击事件
const twoClick = (tier: string | number, oneRow?: any, twoRow?: any, threeRow?: any) => {
    // tier==1 一级  tier==2 二级  tier==3 三级
    let row: any = tier == 1 ? oneRow : tier == 2 ? twoRow : threeRow
    if (props.multiple) {
        // 多选   
        // multiplevValue为选中的数组，点击在数组中筛查
        let index: number = multiplevValue.value.findIndex((item: string) => item == row.categoryId)
        // 存在就删除，不存在就添加
        index != -1 ? multiplevValue.value.splice(index, 1) : multiplevValue.value.push(row.categoryId)
        console.log(multiplevValue.value)
        // 主要针对二级与三级选中时，将children下的数据添加或删除
        pushId(oneRow.categoryId === '' ? treeData.value : row.children, index != -1 ? 'delete' : 'add')
    } else {
        // 单选存入一级二级三级，最后点击完成将id push进一个数组转成字符串
        radioValue.value = tier == 1 ? [oneRow] : tier == 2 ? [oneRow, twoRow] : [oneRow, twoRow, threeRow]
        // 记录选中的id
        radioId.value = row.categoryId
    }
}

const pushId = (row: any, type: string) => {
    if (row && row.length) {
        row.forEach(item => {
            let ind = multiplevValue.value.findIndex(ite => ite == item.categoryId)
            if (type === 'add') {
                if (ind === -1) {
                    multiplevValue.value.push(item.categoryId)
                }
            } else {
                if (ind !== -1) {
                    multiplevValue.value.splice(ind, 1)
                }
            }
            if (item.children && item.children.length) {
                pushId(item.children, type)
            }
        })
    }
}

// 选中状态
const isActive = (id: string) => {
    if (props.multiple) {
        let index = multiplevValue.value.findIndex(item => item == id)
        return index != -1
    } else {
        return id === radioId.value
    }
}
// 重置
const reset = () => {
    if (props.multiple) {
        multiplevValue.value = []
        // emit('update:value', [])
        // emit('onSubmit', [])
    } else {
        radioId.value = ''
        radioValue.value = [{ categoryName: '全部' }]
        // emit('update:value', '')
        // emit('onSubmit', [{ categoryName: '全部' }], 1)
    }
}
// 完成
const submit = () => {
    if (props.multiple) {
        const arr: Array<any> = FindParent(treeData.value, multiplevValue.value)
        emit('update:value', arr)
        emit('onSubmit')
    } else {
        const strArr: Array<string> = []
        radioValue.value.forEach((item: any) => {
            strArr.push(item.categoryId)
        })
        const str = strArr.join(',')
        emit('update:value', str)
        emit('onSubmit', radioValue.value, radioValue.value.length)
    }
}
// 多选时通过多选数组在tree数据中进行遍历递归，返回完整路径的数组
const FindParent = (tree: any, vals: any) => {
    const result: any = [];

    const traverse = (node, path) => {
        if (!node) return;

        // 复制当前路径
        const currentPath: any = [...path, node.categoryId];

        // 检查当前节点是否在目标值列表中
        if (vals.includes(node.categoryId)) {
            result.push(currentPath);
        }

        // 递归遍历子节点
        if (node.children && node.children.length > 0) {
            node.children.forEach(child => traverse(child, currentPath));
        }
    };

    // 从根节点开始遍历
    tree.forEach(rootNode => traverse(rootNode, []));

    return result;
}

</script>

<style lang="less" scoped>
@import url(./style/index.less);

:deep(.van-icon-arrow-left) {
    color: #000;
}

:deep(.van-nav-bar) {
    position: static !important;
    z-index: 6004;
}
</style>